<?php

namespace App\Admin\Controllers;

use App\AdminPermission;
use App\AdminRole;
use App\AdminUser;

class RoleController extends Controller{
    // 管理员列表页面
    public function index(){
        $roles = AdminRole::paginate(10);
        return view('admin.role.index', compact('roles'));
    }
    // 管理员创业页面
    public function create(){
        return view('/admin/role/add');
    }
    // 创建操作
    public function store(){
        $this->validate(request(), [
            'name'=>'required|min:3',
            'description'=>'required',
        ]);

        AdminRole::create(request(['name','description']));
        return redirect('/admin/roles');
    }

    public function permission(AdminRole $role){
        $permissions = AdminPermission::all();
        $myPermission = $role->permissions();

        return view('/admin/role/permission', compact('permissions', 'myPermission', 'role'));
    }

    public function storePermission(\App\AdminRole $role){
        $this->validate(request(),[
            'permissions' => 'required|array'
        ]);

        $permissions = \App\AdminPermission::find(request('permissions'));
        $myPermissions = $role->permissions;

        // 对已经有的权限
        $addPermissions = $permissions->diff($myPermissions);
        foreach ($addPermissions as $permission) {
            $role->grantPermission($permission);
        }

        $deletePermissions = $myPermissions->diff($permissions);
        foreach ($deletePermissions as $permission) {
            $role->deletePermission($permission);
        }
        return back();
    }
}
